/*
 * RepRapExportDialog.cpp
 *
 * Copyright 2012 Pieter Agten
 *
 * This file is part of tltgen.
 *
 * tltgen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * tltgen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with tltgen.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file   RepRapExportDialog.cpp
 * @author Pieter Agten (pieter.agten@gmail.com)
 * @date   13 sep 2012
 */

#include <string>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

#include "CelsiusScale.hpp"

#include "RepRapExportDialog.hpp"

using boost::shared_ptr;
using boost::make_shared;

namespace tltgen {

  BEGIN_EVENT_TABLE(RepRapExportDialog, wxDialog)
  EVT_BUTTON(wxID_OK, RepRapExportDialog::onOkButtonClicked)
  END_EVENT_TABLE()

  RepRapExportDialog::RepRapExportDialog(wxWindow* parent, wxWindowID id, const shared_ptr<ThermistorTable>& thermistorTable,
					 const wxString& title, const wxPoint& pos, const wxSize& size, long style ) :
  wxDialog(parent, id, title, pos, size, style),
    thermistorTable(thermistorTable)
  {
    wxSizer* vbox = new wxBoxSizer(wxVERTICAL);

    wxSizer* gs = new wxGridSizer(1, 2, 3, 3);
    gs->Add(new wxStaticText(this, wxID_ANY, wxT("Table name")), 0, wxALIGN_CENTER_VERTICAL);
    this->txtTableName = new wxTextCtrl(this, wxID_ANY, wxT("temptable"));
    gs->Add(this->txtTableName, 0, wxEXPAND | wxLEFT, 2);

    vbox->Add(gs);

    wxSizer *buttonSizer = CreateSeparatedButtonSizer(wxOK | wxCANCEL);
    vbox->Add(buttonSizer, 0, wxEXPAND | wxALL, 10);
  
    vbox->SetSizeHints(this);
    SetSizer(vbox);
    Centre();
  }

  RepRapExportDialog::~RepRapExportDialog()
  { }

  std::string RepRapExportDialog::getTableName() const
  {
    return std::string(this->txtTableName->GetValue().mb_str());
  }

  void RepRapExportDialog::onOkButtonClicked(wxCommandEvent& event)
  {
    //TODO: validate values

    wxFileDialog saveFileDialog(this, _("Export RepRap file"), wxEmptyString, wxEmptyString, _("C header files (*.h)|*.h"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);

    if (saveFileDialog.ShowModal() == wxID_OK) {
      shared_ptr<TemperatureScale> outputScale = make_shared<CelsiusScale>();      
      RepRapTableWriter writer(getTableName(), outputScale);

      std::string filename = std::string(saveFileDialog.GetPath().mb_str());
      std::ofstream outputFile;
      outputFile.open(filename.c_str(), std::ios_base::out);
      writer.write(outputFile, this->thermistorTable);
      outputFile.close();
    }
    EndModal(wxID_OK);
  }

}


